<?php


namespace App\Commons\Domain\Module\Coin\Service;


use App\Commons\Domain\Core\DomainService;
use App\Commons\Domain\Module\Coin\Entity\CoinEntity;
use App\Commons\Domain\Module\Coin\Entity\ExtractAddressEntity;
use App\Commons\Domain\Module\Coin\Model\Coin;
use App\Commons\Domain\Module\UserCenter\Model\Member;
use Arr;

class CoinService extends DomainService
{
    /**
     * 创建支持币种
     * @param string $name 币种名称
     * @param string $en_name 英文名称
     * @param float $sort_num 排序
     * @param int $status 状态
     * @param array $data ['scale','withdraw_fee','exchange_fee','min_recharge_amount', 'max_withdraw_amount', 'min_withdraw_amount']
     * @return mixed
     */
    public function createCoin(string $name, string $en_name, float $sort_num, int $status, array $data)
    {
        throw_on(Coin::where('name', $name)->first(), 0x600012);

        $coin_data = Arr::only($data, [
            'currency',             // 货币单位：ETH
            'scale',                // 币种精度：6
            'min_recharge_amount',  //最小充值金额：0.01
            'max_withdraw_amount',  //最大提现金额：1000
            'min_withdraw_amount'   //最小提现金额：0.01
        ]);

        return app(CoinEntity::class)->create(compact('name', 'en_name', 'sort_num', 'status') + $coin_data);
    }

    /**
     * 创建提币地址
     * @param Member $member 提币用户
     * @param float $coin_id 币种id
     * @param string $address 提币地址
     * @param string $remark 备注
     * @return mixed
     */
    public function createAddress(Member $member, float $coin_id, string $address, string $remark = '')
    {
        throw_on(!app(CoinEntity::class)->find($coin_id), '暂未支持该币种');

        $member->ExtractAddress->where($address)->first();

        $uid = $member->uid;
        return app(ExtractAddressEntity::class)->create(compact('uid', 'coin_id', 'address', 'remark'));
    }

    /**
     * 删除地址
     * @param Member $member
     * @param string $address_str
     * @return bool
     */
    public function deleteAddress(Member $member, string $address_str)
    {
        $address = app(ExtractAddressEntity::class)->where(['uid' => $member->uid, 'address' => $address_str])->first();

        throw_on(!$address, '提币地址错误');
        return $address->delete();
    }
}
